import re
import sys
sys.path.append("..")
import config
from config import log as log
import requests
import traceback

def sendMaster(msg):
    data = {
        'user_id':config.MASTER,
        'message':msg,
        'auto_escape': False
    }
    cq_url = f'http://{config.HOST}:{config.SENDPORT}/send_private_msg'
    r = requests.post(cq_url,data=data)
    if r.status_code == 200:
        return True
    return False

def send_message_back(sender, msg):
    # config.debug('come into send_msg')
    if sender.type == 'private':
        data = {
            'user_id':sender.id,
            'message':msg,
            'auto_escape': False
        }
        cq_url = f'http://{config.HOST}:{config.SENDPORT}/send_private_msg'
        r = requests.post(cq_url,data=data)
        
    elif sender.type == 'group':
        # config.debug('send group')
        data = {
            'group_id':sender.group_id,
            'message':msg,
            'auto_escape': False
        }
        cq_url = f'http://{config.HOST}:{config.SENDPORT}/send_group_msg'
        r = requests.post(cq_url,data=data)
        
    else:
        return False
    if r.status_code == 200:
        log(f"{sender.cardname or sender.nickname} {sender.id} << {msg}")
        return True
    return False


def send_message_to(type_:str,id_:str, msg:str)->bool:
    # params type_ group or private
    # params id  gid or uid
    # params msg send message
    if type_ == 'private':
        data = {
            'user_id': id_,
            'message':msg,
            'auto_escape': False
        }
        cq_url = f'http://{config.HOST}:{config.SENDPORT}/send_private_msg'
        r = requests.post(cq_url,data=data)
        
    elif type_ == 'group':
        # config.debug('send group')
        data = {
            'group_id': id_,
            'message':msg,
            'auto_escape': False
        }
        cq_url = f'http://{config.HOST}:{config.SENDPORT}/send_group_msg'
        r = requests.post(cq_url,data=data)
        
    else:
        return False
    if r.status_code == 200:
        log(f"{id} << {msg}")
        return True
    return False


def getGroupMemberList(group_id:int):
    '''
    成员字段
        "age": 0,
		"area": "",
		"card": "QQ神经冰",
		"card_changeable": false,
		"group_id": 162100833,
		"join_time": 1454738024,
		"last_sent_time": 1605073590,
		"level": "1",
		"nickname": "提琴",
		"role": "admin",
		"sex": "male",
		"title": "维",
		"title_expire_time": 4294967295,
		"unfriendly": false,
		"user_id": 728000652
    '''
    data = {
        'group_id': group_id
    }
    cq_url = f'http://{config.HOST}:{config.SENDPORT}/get_group_member_list' 
    try:
        res = requests.post(cq_url,data=data).json()
        if res.status_code==200:
            return res['data']
        return None
    except:
        return None




def use_api(urlApi:str,data:dict):
    cq_url = f'http://{config.HOST}:{config.SENDPORT}/{urlApi}' 
    try:
        res = requests.post(cq_url,data=data)
        log(res.text)
        if res.status_code==200:
            return res.json()["data"]
        return None
    except:
        traceback.print_exc()
        return None


# 获取群信息
def get_group_info(groupid:int, no_cache:bool):
    return use_api("get_group_info",{
        "group_id":groupid,
        "no_cache":no_cache
    })

# 获取群列表
def get_group_list():
    return use_api("get_group_list",None)


# 获取某群聊成员列表
def get_group_member_list(group_id:int):
    return use_api("get_group_member_list",{
        "group_id":group_id
    })


# 退出群组
def set_group_leave(groupID:str):
    return use_api("set_group_leave",{
        "group_id":groupID,
        "is_dismiss":False
    })

# 上传群文件
def upload_group_file(groupID:int, filePath:str, upload_name:str, upload_dir:str=None):
    # groupID 群号
    # filePath 本地文件路径
    # upload_name 保存文件名
    # upload_dir 上传路径 默认为根路径
    return use_api("upload_group_file", {
        "group_id": groupID,
        "file": filePath,
        "name": upload_name
        # "folder": upload_dir
        # "folder": "demo"
    })

if __name__=="__main__":
    # print(get_group_info(162100833,True))
    print(get_group_list())